<?php
// WARNING: this will work only in PHP5
// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();
require_once(DOKU_INC.'phpincludes/ACC_Form_Base.php');
//require_once(DOKU_INC.'phpincludes/ACC_DataFile_KF.php');

/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Stephane Chamberland <dokuwiki@meteokid.ca>
 * @date       2009-01-29
 */
class ACC_Form_KF_admin extends ACC_Form_Base {

    var $mailTo = 'keenereserve@accmontreal.ca';
    var $mailToAllowed = array('keenereserve@accmontreal.ca');
    //var $mailTo = 'web@accmontreal.ca';
    //var $mailToAllowed = array('web@accmontreal.ca');
    var $mailToField = 'to_email';
    var $mailFromField = 'from_email';
    var $mailFromNameField = 'from_name';
    var $mailSubjectPrefix = '[KF reserv] ';

    var $mailSubjectFmtName = 'mailSubjectFmt';
    var $mailBodyFmtName = 'mailBodyFmt';

    var $metaFileSuffix = 'keene';
    var $metaFileid = '__keene';

    var $langArray = array(
        'fr' => array(
            'mailSent'       => 'Votre message a &eacute;t&eacute; envoy&eacute;',
            'mailSentError'  => "Erreur d'envoie, SVP contacter l'administrateur a ",
            'msg_confirm'    => '
Merci d\'avoir fait une réservation pour Keene Farm en __cabin__.<br />
Votre réservation est maintenant confirmée (Numero de Confirmation __uid__).<br />
<br />
Détails:<br />
Réservation pour Keene Farm en __cabin__, le __date__ pour __nights__ nuit(s), __people_member__ membres, __people_guests__ non-membres, __people_children__ enfants<br />
Faite par __from_name__ le __now__<br />
<br />
Voici les indications pour vous rendre à Keene Farm, voir la carte sur
<a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">Google maps</a><br />
<a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">
http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11</a><br />
<br />
Notez que <b>les membres doivent avoir leur carte en main</b> puisque le gardien en fera la vérification.<br />
<b>SVP signer le registre des votre arrive à Keene Farm et faites votre payement apres du gardien ou bien à la borne d\'auto enregistrement (montant exacte ou cheque au nom de "ACC Montreal")</b> qui est située près de la pompe à eau et du garage.<br />
Le montant total pour votre séjour sera de: __total_cost__$<br />
<br />
<em>SVP imprimer ou sauvegarder cette confirmation pour référence ulterieur.</em>.<br /><br />Bon Séjour,<br />Le Comite de Keene Farm'
        ),
        'en' => array(
            'mailSent'       => 'Your message was sent sucessfully',
            'mailSentError'  => 'There was an error sending your email, please contact the admin at ',
            'formDescFmt' => 'name keenefarm_admin
action metafile keene
Thanks "All worked ok apparently!"
Fieldset "Keene Farm Admin Selection"
static "You may limit the number of requests displayed below with the following selectors."
select "Status" "All|New|Confirmed|Custodian|Canceled" =All &select_status
select "Cabin/Camping" "All|Cabin|Camping" =All &select_cabin
date "Date From [YYYY-MM-DD]" "=__date_from__" #20 &select_date_from
date "Date To [YYYY-MM-DD]" "=__date_to__" #20 &select_date_to
yesno "Send report by email to the KeeneFarm Reservation Person?" &send_to_kf !
yesno "Send report by email to the Custodian(s)?" &send_to_custodian !
submit "Update Selection" &submit_select
submit "Print Report" &submit_report
Fieldset "Keene Farm Admin Action"
static "Selected action with be applied to checked items below once you submit the form (Take Action button below)."
const  reserv admin
select "Action on selected items" "Confirm|Set_as_Custodian|Set_as_Payed/Pass|Unset_as_Confirmed|Unset_as_Custodian|Unset_as_Payed/Pass|Cancel_Reservation|Delete" &kf_action !
yesno "(not yet working) Send notification of the change by email?" &send_notification !
__items_list__
submit "Take Action"  &submit_action',
            'mailSubjectFmt' => '__cabin__ __reserv__ for __from_name__ on __date__ for __nights__ nights, __people__ people (__people_member__ members, __people_guest__ guests, __people_children__ children)',
            'mailBodyFmt' => 'Keene Farm __reserv__ request
Submited by __from_name__ <__from_email__>
==== Details ====
__ACC_Form_list_all__
=============',
            'error_no_match' => 'We were not able to find a request matching this number/email combination. Please check and try again.',
             'msg_confirm'    => '
Thank you for making a __cabin__ reservation at Keene Farm.<br />
Your reservation is now confirmed (Confirmation number __uid__).<br />
<br />
Details:<br />
Reservation at Keene Farm __cabin__ on __date__ for __nights__ night(s), __people_member__ members, __people_guests__ guests, __people_children__ children<br />
Made by __from_name__ on __now__<br />
<br />
Directions to Keene Farm can be found on <a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">Google maps</a><br />
<a class="urlextern" href="http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11">
http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&msid=106177311759366110668.00000113063b8e45c2cdc&z=11</a><br />
<br />
<b>Members must bring their cards</b> as the custodian will verify them.<br />
<b>Upon your arrival at Keene Farm, please register and pay (exact change or cheque to "ACC Montreal") to the custodian or at the Iron Ranger</b> next to the water pump and of the garage.<br />
The total amount for your stay will be: __total_cost__$<br />
<br />
<em>You may want to print (or save) this confirmation for later reference</em>.<br /><br />Enjoy your stay,<br />The Keene Farm committee',
            'msg_cancel'    => ''
        )
    );

    var $sortKey = 'date';
    var $selectCriterions = NULL;
    var $checked_uids = NULL;
    var $cancelFields = NULL;
    var $metaFile = NULL;

    function _getFormDescFieldsVals($formDescFmtName) {
        //only one possible format, ignore $formDescFmtName
        //TODO: in admin mode, min/max are infinity

        //@unlink($this->_metaFileName());

        $now = date('Y-m-d');
        $date_to_stamp = mktime(0, 0, 0, date("m")+6  , date("d"), date("Y"));
        $date_to = date('Y-m-d',$date_to_stamp);

        if(!is_array($this->selectCriterions))
            $this->selectCriterions = array(
                'select_status' => 'All',
                'select_cabin' => 'All',
                'select_date_from' => $now,
                'select_date_to' => $date_to
                );

        $items_list = '';
        $item_fmt = 'leftcheck "__details__" ! &uid__uid__';
        //$details_fmt = '<b>__date_dow__ __date__ for __nights__ nights x __people__ people in __cabin__</b> [<a href=\'#\' title=\'__All_Details__\'>Details</a>|__reserv_msg_link__][<a href=\'__edit_link__\'>edit</a>]<br />__from_name__ &lt;<a href=\'mailto:__from_email__\'>__from_email__</a>&gt; __from_phone__ [__club__ __club_nb__ __club_checked__]<br />[__status__] [id=<acronymj title=\'__All_Details__\'>__uid__</acronym>] Want to be custodian? __custodian__';
        $details_fmt = '<b>__date_dow__ __date__ for __nights__ nights x __people__ people in __cabin__</b> [__reserv_msg_link__]<br />__from_name__ &lt;<a href=\'mailto:__from_email__\'>__from_email__</a>&gt; __from_phone__ [__club__ __club_nb__ __club_checked__]<br />[__status__] [id=<acronymj title=\'__All_Details__\'>__uid__</acronym>] Want to be custodian? __custodian__';



        $this->metaFile = $this->_metaFile_get($this->metaFileid);
        $sortlist = array();
        $keeplist = array();
        foreach($this->metaFile as $uid => $item) {
            //select_status "All|New|Confirmed|Custodian|Canceled"
            //select_cabin "All|Cabin|Camping"
            //select_date_from
            //select_date_to
            $keep = true;
            if(!is_null($this->selectCriterions)) {
                if ($this->selectCriterions['select_status'] != 'All' &&
                    strtolower($this->selectCriterions['select_status']) != $item['status'])
                    $keep = false;
                if ($this->selectCriterions['select_status'] == 'Confirmed' &&
                    strtolower($item['status']) == 'custodian')
                    $keep = true;
                if ($this->selectCriterions['select_cabin'] != 'All' &&
                    $this->selectCriterions['select_cabin'] != $item['cabin'])
                    $keep = false;
                if ($keep) {
                    $d_item = strtotime($item['date']);
                    $d_item2 = $d_item + 24*3600*(max(0,$item['nights']-1));
                    $d_min = strtotime($this->selectCriterions['select_date_from']);
                    $d_max = strtotime($this->selectCriterions['select_date_to']);
                    if($d_item2<$d_min || $d_item>$d_max) $keep = false;
                }
            }
            if($keep){
                $d_item = strtotime($item['date']);
                $item['date_dow'] = date('D',$d_item);
                $item['club_checked'] = ''; //TODO:
                if($item['club_nb']) $item['club_checked'] = '(Not Checked)'; //TODO:

                $item['reserv_msg_link'] = 'No Msg';
                if($item['msg']) $item['reserv_msg_link'] = '<acronym title=\''.str_replace("\n",' ',$item['msg']).'\'>View Msg</acronym>';
                $sortlist[$uid] = $item[$this->sortKey];
                $details = $this->_str_replace_from_values($details_fmt,$item);
                $keeplist[$uid] =  $this->_str_replace_from_values($item_fmt,array('uid'=>$uid,'details'=>$details));
            }
        }
        if(count($keeplist)) {
            asort($sortlist);
            foreach($sortlist as $k=>$v) $items_list .= $keeplist[$k]."\n";
        } else {
            $items_list = 'static "No active reservation request in Selection"';
        }

        return array(
            '__items_list__' => $items_list,
            '__date_from__' => $now,
            '__date_to__' => $date_to,
            );
    }

    function _postcheckpost($data) {
        $errors = array();
        $values = $this->buro->_collectpost($data);
        $idx=999;

        //echo '<pre> values ';
        //print_r($values);
        //echo '</pre>';

        if($values['submit_select']){
            $this->selectCriterions = $values;
            $errors['submit_select'] = 1; //trigger an error to get the form back with updated values
            msg('Updated Selection.',0);
        }
        if($values['submit_report']){
            $this->selectCriterions = $values;
            $errors['submit_report'] = 1; //trigger an error to get the form back with updated values
            //TODO: msg with list of reservations
            msg($this->_action_report(),1);
        }
        if($values['submit_action']){
            if (!$values['kf_action']) {
                $errors['kf_action'] = 1;
                msg('You must select an Action.',-1);
            }

            $this->checked_uids = array();
            foreach($values as $k=>$v){
                if(substr($k,0,3)=='uid' && $v=='Yes') {
                    $this->checked_uids[] = substr($k,3);
                }
            }
            if(!count($this->checked_uids)) {
                $errors[$idx++] = 1;
                msg('You must select/check one or more item to take action on.',-1);
            } else if(count($this->metaFile)) {
                foreach($this->checked_uids as $uid){
                    $item = $this->metaFile[$uid];
                    //TODO: if cancel/delete custodian
                    switch($values['kf_action']){
                        case 'Confirm':
                            //TODO: error if no custodian for the periode
                        break;
                        case 'Cancel_Reservation':
                        case 'Unset_as_Confirmed':
                        case 'Unset_as_Custodian':
                        case 'Delete':
                            if($item['status'] == 'custodian')
                                //TODO: check if it does affect others
                                msg('Warning you are modifying a custodian\'s status, this may affect Others.',0);
                        break;
                        case 'Set_as_Custodian':
                            if($item['custodian'] == 'no') {
                                $errors['uid'.$uid] = 1;
                                msg('You cannot set uid='.$uid.' as custodian as he/she does not want to.',-1);
                                //TODO: check if on blacklist
                            }
                        break;
                        }
                    //TODO: if set many custodian
                }
            //TODO: check for custodian: cannot confirm w/o one, may limit the number of custodian for a single day; if cancel/delete
            }

            //echo '<pre> checked_uids ';
            //print_r($checked_uids);
            //echo '</pre>';
        }

        /*
        $metaFile = $this->_metaFile_get($this->metaFileid);
        $searchOk = $this->_metaFile_search($metaFile,array('from_email'=>$values['from_email']),$values['uid']);
        if (!count($searchOk)) {
            $errors['from_email'] = 1;
            $errors['uid'] = 1;
            msg($this->getLang('error_no_match'),-1);
        } else {
            //unset($metaFile[$values['uid']]);
            $metaFile[$values['uid']]['status'] = 'canceled';
            $metaFile[$values['uid']]['msgc'] = $values['msgc'];
            $metaFile[$values['uid']]['nowc'] = date('c');
            $this->cancelFields = $metaFile[$values['uid']];
            $this->metaFile = $metaFile;
            //TODO: if was custodian and in less than 3d, may add in black list of custodian + reflect on other reservations for these dates
        }
        */

        return $errors;
    }


    function _sub_list($date0,$date1,$selFunc='',$metaFile=NULL) {
        if(is_null($metaFile) || !is_array($metaFile)) {
            $metaFile = $this->_metaFile_get($this->metaFileid);
            $this->metaFile = $metaFile;
        }
        $d_min = strtotime($date0);
        $d_max = strtotime($date1);
        $subMetaFile = array();
        foreach($metaFile as $uid => $item){
            $d_item = strtotime($item['date']);
            $d_item2 = $d_item + 24*3600*(max(0,$item['nights']-1));
            $keep=false;
            if($d_item2>=$d_min && $d_item<=$d_max){
                $keep=true;
                if($selFunc) $keep=$this->$selFunc($item); #TODO: check if $selFunc exists
                if($keep) $subMetaFile[$uid] = $item;
            }
            #print(date('Y-m-d',$d_item2).' >= '.date('Y-m-d',$d_min).' && '.date('Y-m-d',$d_item).' <= '.date('Y-m-d',$d_max)." : ".$keep."-".$selFunc."\n");
        }
        return $subMetaFile;
    }

    function _selActiveReserv($item) {
        if (in_array(strtolower($item['status']),array('new','confirmed','custodian'))) return true;
        return false;
    }

    function _selCustodian($item) {
        if (strtolower($item['status']) == 'custodian') return true;
        return false;
    }

    function _selCabin($item) {
        if (strtolower($item['cabin']) == 'cabin') return true;
        return false;
    }

    function _selCamping($item) {
        if (strtolower($item['cabin']) == 'camping') return true;
        return false;
    }

    function _nbPeople($item) {
        $people = 0;
        foreach(array('people_member','people_guests','people_children') as $k) {
            if (is_numeric($item[$k])) $people += $item[$k];
        }
        return $people;
    }

    function _action_report() {
        #print('<pre>');

        $msg = '';
        #get list of reserv in date range
        $date0 = $this->selectCriterions['select_date_from'];
        $date1 = $this->selectCriterions['select_date_to'];
        $subList = $this->_sub_list($date0,$date1,'_selActiveReserv');

        #print('select_date_from:'.$date0.':'.strtotime($date0)."\n");
        #print('select_date_to  :'.$date1.':'.strtotime($date1)."\n");
        #print('subList  :'.count($this->metaFile).':'.count($subList)."\n");

        $thatDay = strtotime($this->selectCriterions['select_date_from']);
        $allCustodianList = array();
        while($thatDay<=strtotime($this->selectCriterions['select_date_to'])){
            $date0 = date('Y-m-d',$thatDay);
            $date1 = $date0;
            $dayList       = $this->_sub_list($date0,$date1,'',$subList);
            $custodianList = $this->_sub_list($date0,$date1,'_selCustodian',$dayList);
            $cabinList     = $this->_sub_list($date0,$date1,'_selCabin',$dayList);
            $campingList   = $this->_sub_list($date0,$date1,'_selCamping',$dayList);
            #print($date0.':'.count($this->metaFile).':'.count($subList).':'.count($dayList)."\n");
            #print($date0.':'.count($this->metaFile).':'.count($subList).':'.count($custodianList)."\n");
            #print($date0.':'.count($this->metaFile).':'.count($subList).':'.count($cabinList)."\n");
            #print($date0.':'.count($this->metaFile).':'.count($subList).':'.count($campingList)."\n");

            $msg .= $this->_action_report_print($date0,$custodianList,$cabinList,$campingList);

            $allCustodianList = array_merge($allCustodianList,$custodianList);
            $thatDay += 24*3600;
        }
        #print('</pre>');

        if($msg){
            $msg = '<b>Keene Farm Reservations Report</b> ('.$this->selectCriterions['select_date_from'].' - '.$this->selectCriterions['select_date_to'].')<br /><br />'."\n\n" . $msg;

            $msg .= "<br />Legend -- N:Nights ; P:People ; M:Members ; G:Guest ; C:Children ; *:Need to Check Number<br />\n";
        }else{
            $msg = "No active reservation the periode (".$this->selectCriterions['select_date_from']." - ".$this->selectCriterions['select_date_to'].")<br />"."\n";
        }

        $msg .= $this->_action_report_email($msg,$allCustodianList);

        return $msg;
    }

    function _action_report_print($mydate,$custodianList,$cabinList,$campingList){
        if(!count($cabinList) && !count($campingList)) return '';

        $details_custodian = 'Custodian: __from_name__ &lt;<a href=\'mailto:__from_email__\'>__from_email__</a>&gt; __from_phone__ [__club__ __club_nb__] (uid=__uid__)<br /><br />'."\n\n";
        $details_hdr = '<table class="inline" cellpadding="5" cellspacing="0" border="1"><tbody><tr><th>Name</th><th>Nights</th><th>People (Member, Guest, Child)</th><th>Club # (*=to Check)</th><th>Car</th><th>Cost</th><th>Status</th><th>Payed/Pass</th></tr>'."\n";
        $details_fmt = '<tr><td>__from_name__</td><td>__nights__N __first_night__</td><td>__people__P (__people_member__M, __people_guests__G, __people_children__C)</td><td>__club__ __club_nb____club_checked__</td><td>__car__</td><td>__total_cost__$</td><td>__status__</td><td>__payed__</td></tr>'."\n";
        $details_ftr = '</tbody></table><br />';

        $msg = '';
        $msg .= "<b>== ".$mydate." ================================</b><br /><br />"."\n\n";
        if(!count($custodianList)){
            $msg .= '<b>No Custodian set for that date Yet!!!</b><br /><br />'."\n\n";
        } else {
            foreach($custodianList as $uid => $item){
                $msg .= $this->_str_replace_from_values($details_custodian,$item);
            }
        }
        $reservList = array(
            'cabin'   => $cabinList,
            'camping' => $campingList
            );
        foreach(array('cabin','camping') as $cabin){
            $msg .= "<b>-- ".$cabin." ----------------------</b><br /><br />"."\n\n";

            $people = 0;
            $new_people = 0;
            foreach($reservList[$cabin] as $uid => $item) {
                $nb = $this->_nbPeople($item);
                $people += $nb;
                if($item['date'] == $mydate) $new_people += $nb;
            }
            $msg .= $people.' ('.$new_people.' new) '.$cabin.' Reservations for '.$mydate.'.<br /><br />'."\n\n";

            if(count($reservList[$cabin])){
                $msg .= $details_hdr;
                foreach($reservList[$cabin] as $uid => $item){
                    $item['club_checked'] = '';
                    if ($item['club']!='None/Other') $item['club_checked'] = '*'; //TODO:
                    if(!isset($item['payed'])) $item['payed'] = '';
                    $item['first_night'] = '';
                    if($item['date'] == $mydate) $item['first_night'] = '(new)';
                    foreach(array('people_member','people_guests','people_children') as $k) {
                        if (!is_numeric($item[$k])) $item[$k]=0;
                    }
                    $msg .= $this->_str_replace_from_values($details_fmt,$item);
                }
                $msg .= $details_ftr;
            }
        }
        return $msg;
    }

    function _action_report_email($msg0,$allCustodianList){
        $send_to_report = array();
        if(isset($this->selectCriterions['send_to_kf']) &&
            strtolower($this->selectCriterions['send_to_kf']) == 'yes'){
            $send_to_report[$this->mailTo] = 'ACC Montreal Keene Farm';
        }
        if(isset($this->selectCriterions['send_to_custodian']) &&
            strtolower($this->selectCriterions['send_to_custodian']) == 'yes'){
            foreach($allCustodianList as $uid => $item){
                $send_to_report[$item['from_email']] = $item['from_name'];
            }
        }
        if(count($send_to_report)){
            $fromName = 'ACC Montreal';
            $fromEmail = 'web@accmontreal.ca';
            $from = $fromName.' <'.$fromEmail.'>';

            $to = '';
            foreach($send_to_report as $toEmail => $toName){
                $to .= $toName.' <'.$toEmail.'>, ';
            }
            $body = '<html><body>'.$msg0.'</body></html>';
            $ok = mail_send_html($to, $this->mailSubjectPrefix.'Keene Farm Reservations Report', $body, $from);
            if($ok){
                $msg = "<p><b>Report eMail Sent to</b>:".hsc($to)."</p>\n";
            }else{
                $msg = "<p><b>Problem sending Report eMail to</b>:".hsc($to)."</p>\n";
            }
        }
        return $msg;
    }

    function _action_report0() {
        $now = date('Y-m-d');
        $date_to_stamp = mktime(0, 0, 0, date("m")+6  , date("d"), date("Y"));
        $date_to = date('Y-m-d',$date_to_stamp);

        if(!is_array($this->selectCriterions))
            $this->selectCriterions = array(
                'select_status' => 'New',
                'select_cabin' => 'Cabin',
                'select_date_from' => $now,
                'select_date_to' => $date_to
                );

        $this->metaFile = $this->_metaFile_get($this->metaFileid);
        $datelist = array();
        $keeplist = array();
        foreach($this->metaFile as $uid => $item) {
            $keep = true;
            if(!is_null($this->selectCriterions)) {
                if (!in_array(strtolower($item['status']),array('new','confirmed','custodian')))
                    $keep = false;
                if ($keep) {
                    $d_item = strtotime($item['date']);
                    $d_item2 = $d_item + 24*3600*(max(0,$item['nights']-1));
                    $d_min = strtotime($this->selectCriterions['select_date_from']);
                    $d_max = strtotime($this->selectCriterions['select_date_to']);
                    if($d_item2<$d_min || $d_item>$d_max) $keep = false;
                }
            }
            if($keep){
                $d_item = strtotime($item['date']);
                $keeplist[] = $uid;
                $datelist[] = $d_item;
            }
        }

        $custo_list = array();
        $report = array();
        $datelist = array_unique($datelist);
        sort($datelist);
        foreach($datelist as $mydate) {
            $r_custo = array();
            $r_list['cabin'] = array('old'=>array(),'new'=>array());
            $r_list['camping'] = array('old'=>array(),'new'=>array());

            foreach($keeplist as $uid){
                $item = $this->metaFile[$uid];
                $cabin = strtolower($item['cabin']);
                $d_item2 = strtotime($item['date']);
                $d_item3 = $d_item2 + 24*3600*(max(0,$item['nights']));
                if($d_item2 == $mydate) {
                    $r_list[$cabin]['new'][] = $uid;
                } else if($mydate>$d_item2 && $mydate<$d_item3) {
                    $r_list[$cabin]['old'][] = $uid;
                }
                if(strtolower($item['status'])=='custodian') {
                    $r_custo[] = $uid;
                    $custo_list[] = $uid;
                }
            }

            $report[strftime('%a %d %b %Y',$mydate)]['custo'] = $r_custo;
            $report[strftime('%a %d %b %Y',$mydate)]['cabin'] = $r_list['cabin'];
            $report[strftime('%a %d %b %Y',$mydate)]['camping']  = $r_list['camping'];
        }


        $details_custodian = 'Custodian: __from_name__ &lt;<a href=\'mailto:__from_email__\'>__from_email__</a>&gt; __from_phone__ [__club__ __club_nb__] (uid=__uid__)<br /><br />'."\n\n";
        $details_hdr = '<table class="inline" cellpadding="5" cellspacing="0" border="1"><tbody><tr><th>Name</th><th>Nights</th><th>People (Member, Guest, Child)</th><th>Club # (*=to Check)</th><th>Car</th><th>Cost</th><th>Status</th><th>Payed/Pass</th></tr>'."\n";
        $details_fmt = '<tr><td>__from_name__</td><td>__nights__N</td><td>__people__P (__people_member__M, __people_guests__G, __people_children__C)</td><td>__club__ __club_nb____club_checked__</td><td>__car__</td><td>__total_cost__$</td><td>__status__</td><td>__payed__</td></tr>'."\n";
        $details_ftr = '</tbody></table><br />';

        $msg ='';
        foreach($report as $mydate => $r_list){
            $msg .= "<b>==== ".$mydate." ====</b><br /><br />"."\n\n";
            foreach($r_list['custo'] as $uid){
                $item = $this->metaFile[$uid];
                $msg .= $this->_str_replace_from_values($details_custodian,$item);
            }
            if(!count($r_list['custo'])) $msg .= '<b>No Custodian set for that date Yet!!!</b><br /><br />'."\n\n";

            foreach(array('cabin','camping') as $cabin){
                $msg .= "<b>-- ".$cabin." --</b><br /><br />"."\n\n";
                $new_people = count($r_list[$cabin]['new']);
                $people = count($r_list[$cabin]['old']) + $new_people;
                $msg .= $people.' ('.$new_people.' new) '.$cabin.' Reservations for '.$mydate.'.<br /><br />'."\n\n";
                if(count($r_list[$cabin]['new'])){
                    $msg .= $details_hdr;
                    foreach($r_list[$cabin]['new'] as $uid){
                        $item = $this->metaFile[$uid];
                        $item['club_checked'] = '';
                        if ($item['club']!='None/Other') $item['club_checked'] = '*'; //TODO:
                        if(!isset($item['payed'])) $item['payed'] = '';
                        $msg .= $this->_str_replace_from_values($details_fmt,$item);
                    }
                    $msg .= $details_ftr;
                }
            }
        }
        $msg = str_replace('Zero','0',$msg);

        if($msg){
            $msg = '<b>Keene Farm Reservations Report</b> ('.$this->selectCriterions['select_date_from'].' - '.$this->selectCriterions['select_date_to'].')<br /><br />'."\n\n" . $msg;

            $msg .= "<br />Legend -- N:Nights ; P:People ; M:Members ; G:Guest ; C:Children ; *:Need to Check Number<br />\n";
        }else{
            $msg = "No active reservation the periode (".$this->selectCriterions['select_date_from']." - ".$this->selectCriterions['select_date_to'].")<br />"."\n";
        }

        $send_to_report = array();
        if(isset($this->selectCriterions['send_to_kf']) &&
            strtolower($this->selectCriterions['send_to_kf']) == 'yes'){
            $send_to_report[$this->mailTo] = 'ACC Montreal Keene Farm';
        }
        if(isset($this->selectCriterions['send_to_custodian']) &&
            strtolower($this->selectCriterions['send_to_custodian']) == 'yes'){
            foreach($custo_list as $uid){
                $send_to_report[$this->metaFile[$uid]['from_email']] = $this->metaFile[$uid]['from_name'];
            }
        }
        if(count($send_to_report)){
            $fromName = 'ACC Montreal';
            $fromEmail = 'web@accmontreal.ca';
            $from = $fromName.' <'.$fromEmail.'>';

            $to = '';
            foreach($send_to_report as $toEmail => $toName){
                $to .= $toName.' <'.$toEmail.'>, ';
            }
            $body = '<html><body>'.$msg.'</body></html>';
            $ok = mail_send_html($to, $this->mailSubjectPrefix.'Keene Farm Reservations Report', $body, $from);
            if($ok){
                $msg .= "<p><b>Report eMail Sent to</b>:".hsc($to)."</p>\n";
            }else{
                $msg .= "<p><b>Problem sending Report eMail to</b>:".hsc($to)."</p>\n";
            }
        }
        return $msg;
    }


    function _action_ok($data,$thanks) {
        $values = $this->buro->_collectpost($data);

        //Confirm|Set_as_Custodian|Unset_as_Custodian|Cancel_Reservation|Delete
        if($values['submit_action'] && count($this->checked_uids)) {
            $msg = '';
            foreach($this->checked_uids as $uid) {
                switch($values['kf_action']){
                    case 'Cancel_Reservation':
                        $this->metaFile[$uid]['status'] = 'canceled';
                    break;
                    case 'Confirm':
                        if ($this->metaFile[$uid]['status'] != 'custodian')
                            $this->metaFile[$uid]['status'] = 'confirmed';
                        //TODO: send confirmation email
                    break;
                    case 'Unset_as_Confirmed':
                        $this->metaFile[$uid]['status'] = 'new';
                    break;
                    case 'Set_as_Custodian':
                        $this->metaFile[$uid]['status'] = 'custodian';
                    break;
                    case 'Unset_as_Custodian':
                        $this->metaFile[$uid]['status'] = 'confirmed';
                    break;
                    case 'Set_as_Payed/Pass':
                        $this->metaFile[$uid]['payed'] = 'Payed';
                    break;
                    case 'Unset_as_Payed/Pass':
                        $this->metaFile[$uid]['payed'] = false;
                    break;
                    case 'Delete':
                        unset($this->metaFile[$uid]);
                    break;
                }
                $msg .= $uid.', ';
            }
            $ok = $this->_metaFile_save($this->metaFile,$this->metaFileid);
            if ($ok) {
                return 'Did "'.$values['kf_action'].'" on items: '.$msg.'<br />[pending implementation] A notification email was sent.';
            } else {
                msg('Problem taking requested action',-1);
                return '';
            }
        }

        /*
        if (!is_null($this->metaFile)) $ok = $this->_metaFile_save($this->metaFile,$this->metaFileid);

        $people = 0;
        foreach(array('people_member','people_guests','people_children') as $k) {
            if (is_numeric($this->cancelFields[$k])) $people += $this->cancelFields[$k];
        }

        $values = $this->buro->_collectpost($data);
        $this->cancelFields['people'] = $people;
        $this->cancelFields['msgc'] = $values['msgc'];
        $this->cancelFields['reserv'] = $values['reserv'];
        $ok = $this->_sendMail($this->cancelFields);

        if ($ok) {
            $sr = array();
            foreach($this->cancelFields as $k=>$v) $sr['__'.$k.'__'] = $v;
            return str_replace(array_keys($sr),array_values($sr),$this->getLang('msg_cancel'));
        }
        msg($this->getLang('mailSentError'));
        return false;
        */
        return $thanks;
    }

}

$my_contact_form = new ACC_Form_KF_admin($this);
print($my_contact_form->_action_show_form());
